from constants.consts import USER_AGENT_GITCODE
from db import utils
from logger import logger
from sub_events.base_event import BaseEvent

LOGGER = logger.CustomLogger()

class ShowOwners(BaseEvent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.event_name_zh: str = "展示CODEOWNERS成员"
        self.event_name_en: str = "Show CodeOwners"

    def pre_execute(self) -> bool:
        return self.hook.user_agent == USER_AGENT_GITCODE

    def execute(self):
        new_code_owners = []
        for approver in self.hook.get("merge_request", {}).get("approver_list", []):
            new_code_owners.append(approver.get("name"))
        added, deleted = utils.update_pr_code_owners(self.hook, new_code_owners)
        for group in added:
            comment = f"修改责任田 @{group} 相关代码, 请根据修改内容联系以下人员检视后评论\"pass\"后消分:\n"
            user_infos = self.OCM.owner_config['userInfos']
            group_members = self.OCM.owner_config["groups"].get(group, [])
            for member in group_members:
                comment += f"{user_infos[member]['info']} @{member}\n"
            self.comment = comment
            LOGGER.info(
                f"""[{self.hook.pr_number}] {comment}""")
